package com.example.labb2da523b;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;

import com.example.labb2da523b.db.Expense;
import com.example.labb2da523b.db.SqlHelper;

public class CircleView extends View {
	private int width;
	private int height;
	private RectF arcSpace;
	SqlHelper db = new SqlHelper(this.getContext());
	
	private double[] values={0,0,0,0};
	private String[] categories={"Food","Transportation","Cloths","Hobby"};
	private int totalValues;
	private double thisSize;
	private float prevAngle=0;
	private Expense expense;
	private int budget;
	DecimalFormat df = new DecimalFormat("###.##");

	ArrayList<Expense> expenses = new ArrayList<Expense>();
	
	private int[] COLORS={Color.argb(255, 8, 167, 232),Color.argb(255, 46, 43, 132),
			Color.argb(255, 209, 95, 22),Color.argb(255, 236, 164, 28)};
	private Paint circlePaint;
	
	public CircleView(Context context) {
		super(context);
		try {
			getExpenses();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			db.open();
			budget = db.getBudget();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			budget = 0;
			e.printStackTrace();
		}
		
	}
	
	private void getExpenses() throws SQLException {
		db.open();
		expenses = db.getAllExpenses();
		db.close();
		for(int i = 0; i<expenses.size();i++) {
			expense = expenses.get(i);
			if(expense.getCategory().equals("Food")) {
				values[0] += expense.getSum();
			}
			if(expense.getCategory().equals("Transportation")) {
				values[1] += expense.getSum();
			}
			if(expense.getCategory().equals("Cloths")) {
				values[2] += expense.getSum();
			}
			if(expense.getCategory().equals("Hobby")) {
				values[3] += expense.getSum();
			}
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		circlePaint = new Paint();
		circlePaint.setAntiAlias(true);
		width = this.getWidth()/2;
		height = this.getHeight()/2;

		arcSpace = new RectF(width-200, height-200, width+200, height+200);		
		
		for(int i = 0; i < values.length; i++) {
			totalValues = (int) (totalValues+values[i]);
		}

		for(int i = 0; i < values.length; i++) {
			circlePaint.setColor(COLORS[i]);
			thisSize = values[i]/totalValues;
			float angle = (float) (360*thisSize);
			canvas.drawArc(arcSpace, prevAngle, angle, true, circlePaint);
			circlePaint.setTextSize(30);
			
			canvas.drawText(categories[i]+": " + values[i] +":-"+ "  (" + df.format(thisSize*100) + "%"+")", 50, 100+i*50, circlePaint);
			prevAngle=angle+prevAngle;
		}
		circlePaint.setColor(Color.BLACK);
		circlePaint.setTextSize(40);
		canvas.drawText("Money Left: " + (budget-totalValues), 150, 1000, circlePaint);
	}
}
